package com.sugar.base.core;

import java.io.IOException;
import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

public class MyBatisConnSupport {

	private final static Logger logger = Logger.getLogger(MyBatisConnSupport.class.getClass()) ;
	
	private static SqlSessionFactory factory ;
	
	private static String path ;
	
	public MyBatisConnSupport() {}
 
	public void setIbatisConfigLocation(Resource ibatisConfigLocation) {
		
		if(null == ibatisConfigLocation || "".equals(ibatisConfigLocation)) {
			logger.debug("[....Log4j]：mybatis-config.xml配置文件不存在或错误..." ) ;
			return ;
		}
		path = ((ClassPathResource)ibatisConfigLocation).getPath();
		if(null == factory) {
			try {
				Reader reader = Resources.getResourceAsReader(path) ;
				factory = new SqlSessionFactoryBuilder().build(reader) ;
			} catch (IOException e) {
				logger.debug("[....Log4j]：无法加载MyBatis配置文件[路径错误...]" ) ;
				e.printStackTrace();
			}
		}
	}
	
	public SqlSession getSqlSession() {
		if(null == factory) {
			logger.debug("[....Log4j]：无法构建SqlSessionFactory" ) ;
			return null;
		}
		return factory.openSession() ;
	}
	
/*	public static void main(String[] args) {
		ClassPathXmlApplicationContext c = new ClassPathXmlApplicationContext("bean.xml") ;
		
		MyBatisConnSupport s =(MyBatisConnSupport) c.getBean("myBatisSupport") ;
		
		System.out.println(factory);
		
		System.out.println("------------------");
		System.out.println(s.getSqlSession()) ;
		System.out.println(s.getSqlSession()) ;
		
	}*/
}
